import RouterContainer from '@/components/router-container.vue'
import type { SysMenuEx } from '@/types/sys-menu-tree';
import Dashboard from '@/views/dashboard/dashboard.vue'
import type { Router, RouteRecordRaw } from "vue-router";

/**
 * 动态路由帮助类
 */
export default class DynamicRouterHelper {

  /**
   * 组装路径
   * @param strs 路径列表
   */
  public static splicePath(strs: string[]): string {
    return strs.filter(x => x).join("/");
  }

  /**
   * 访问路径转name
   * @param path 
   */
  public static pathToName(path: string): string {
    return path.replace(/\//g, "_");
  }

  /**
   * 按ID递归查找路由
   * @param id 路由ID
   */
  public static findById(id: number, menus: SysMenuEx[]): SysMenuEx | null {
    let sysMenuTree: SysMenuEx | null = null;

    for (const menu of menus) {
      if (menu.id === id) {
        sysMenuTree = menu;
        break;
      } else if (menu.children && menu.children.length) {
        sysMenuTree = DynamicRouterHelper.findById(id, menu.children);
      }
    }

    return sysMenuTree;
  }

  // 递归组装路由树
  private static recursionRouters = (modules: Record<string, () => Promise<unknown>>, data: SysMenuEx[], parent?: SysMenuEx): RouteRecordRaw[] => {
    const address = `../views/$1.vue`;
    return data
      .map(x => {
        const path = DynamicRouterHelper.splicePath([parent?.frontEndRouter || "", x.frontEndRouter]);
        const asyncComponent = modules[address.replace("$1", x.componentPath)];
        // 仪表盘页面直接使用组件不异步加载
        const isHome = path === "/";
        return {
          path,
          name: DynamicRouterHelper.pathToName(path),
          // 组件路径不存在时
          component: x.componentPath ? (isHome ? Dashboard : asyncComponent) : RouterContainer,
          meta: { title: x.name },
          children: x.children && x.children.length && DynamicRouterHelper.recursionRouters(modules, x.children, x) || []
        }
      })
      // 过滤掉没有实际组件的路由
      .filter(x => x.component);
  }

  /**
   * 初始化路由
   */
  public static initRouters = (mentList: SysMenuEx[], router: Router) => {
    const routers: SysMenuEx[] = mentList || [];
    const modules = import.meta.glob('../views/**/*.vue');
    // 组装数据
    const records = DynamicRouterHelper.recursionRouters(modules, routers);

    for (const record of records) {
      router.addRoute(record);
    }
  }

  /**
   * 处理数据组装成树结构
   * @param data 数据
   * @param rootId 根节点id
   */
  public static handlerTree = (data: any[]): any[] => {
    const copy: any[] = JSON.parse(JSON.stringify(data));
    // 利用引用关系组装
    for (const x of copy) {
      const filter = copy.filter(v => v.parentId === x.id);
      if (filter.length) {
        x.children = filter;
      }
    }
    // 组装完毕后取出第一级即可 上边组装会利用对象引用的关系自动将第三级及一下的子节点添加到第一级节点
    const tree: any[] = copy.filter(x => !x.parentId);
    return copy.filter(x => !x.parentId);
  }
}